export class FormData extends Map<string, FieldItem> {
}

export interface FieldItem {
    value: any;
    validators?: Array<Validation>,
}

export interface Validation {
    name: Validations;
    message?: string;
    valid: boolean;
}

export enum Validations {
    REQUIRED
}

export class Validator {
    static validate(dataObj: FormData): FormData {
        if (dataObj === undefined) {
            return dataObj;
        }
        dataObj.forEach(item => {
            this.validation(item);
        });
        return dataObj;
    }

    static validateItem(dataObj: FormData, field: string): FieldItem | null {
        let item = dataObj.get(field);
        if (item === undefined) {
            return null;
        }
        return Validator.validation(item);
    }

    static validation(item: FieldItem): FieldItem {
        if (item.validators === undefined) {
            return item;
        }
        // let result = {...item};
        for (let i = 0; i < item.validators.length; i++) {
            let validator = item.validators[i];
            // let targetValidator = result.validators[i];
            switch (validator.name) {
                case Validations.REQUIRED:
                    if (item.value === undefined || item.value === '') {
                        validator.valid = false;
                        // valid = valid && false;
                    } else {
                        validator.valid = true;
                    }
                    break;
                default:
                    break;
            }
        }
        return item;
    }

    static hasError(dataObj: FormData): boolean {
        if (dataObj === undefined) {
            return false;
        }
        let result = false;
        dataObj.forEach(item=>{
            if (item.validators === undefined || item.validators.length === 0) {
                result = false;
                return;
            }
            for (const validation of item.validators) {
                if (!validation.valid) {
                    result = true;
                    return;
                }
            }
        });
        return result;
    }

    static getData(dataObj: FormData) {
        let result: Map<string, any> = new Map<string, any>();
        dataObj.forEach((item,key)=>result.set(key,item.value));
        return result;
    }
}
